package com.gouda.core.dao;

import com.google.common.collect.Maps;
import com.gouda.core.entity.AdvertisementEntity;
import com.gouda.core.enums.GeneralStateEnum;
import com.gouda.core.utils.CacheKey;
import com.hephaestus.cache.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.amethyst.atlas.db.MagicDao;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by souu on 15/12/5.
 */
@Slf4j
@Repository
public class AdvertisementDao extends MagicDao {

    private static final String BASE_SQL_ID = "select id from advertisement";

    public List<Long> getDefaultAdvertisement() {
        List<Long> ids = (List<Long>) CacheUtil.getInstance().get(CacheKey.getDefaultAdvertisement());
        if (CollectionUtils.isEmpty(ids)) {
            String sql = BASE_SQL_ID + " where isdefault = :isDefault order by create_time desc";
            Map<String, Object> param = Maps.newHashMap();
            param.put("isDefault", GeneralStateEnum.YES.getCode());
            ids = super.listColumns(AdvertisementEntity.class, sql, param, Long.class);
            if (CollectionUtils.isEmpty(ids)) {
                return null;
            }
            try {
                CacheUtil.getInstance().add(CacheKey.getDefaultAdvertisement(), ids, DateUtils.addHours(new Date(), 1));
            } catch (InterruptedException e) {
                log.error("getDefaultAdvertisement cache error:{}", e.getMessage());
            }
        }
        return ids;
    }
}
